<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label=" 资产编号" prop="assetNumber">
        <el-input
          v-model="queryParams.assetNumber"
          placeholder="请输入 资产编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label=" 资产名称" prop="assetName">
        <el-input
          v-model="queryParams.assetName"
          placeholder="请输入 资产名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label=" 信息卡分类" prop="infoCardCategory">
        <el-input
          v-model="queryParams.infoCardCategory"
          placeholder="请输入 信息卡分类"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label=" 资产分类" prop="assetCategory">
        <el-input
          v-model="queryParams.assetCategory"
          placeholder="请输入 资产分类"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label=" 资产分类编码" prop="assetCategoryCode">
        <el-input
          v-model="queryParams.assetCategoryCode"
          placeholder="请输入 资产分类编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label=" 资产门类" prop="assetClass">
        <el-input
          v-model="queryParams.assetClass"
          placeholder="请输入 资产门类"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label=" 数量/面积" prop="quantityArea">
        <el-input
          v-model="queryParams.quantityArea"
          placeholder="请输入 数量/面积"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label=" 取得方式" prop="acquisitionMethod">
        <el-input
          v-model="queryParams.acquisitionMethod"
          placeholder="请输入 取得方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label=" 取得日期" prop="acquisitionDate">
        <el-input
          v-model="queryParams.acquisitionDate"
          placeholder="请输入 取得日期"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label=" 单位名称" prop="unitName">
        <el-input
          v-model="queryParams.unitName"
          placeholder="请输入 单位名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label=" 清查编号" prop="inventoryNumber">
        <el-input
          v-model="queryParams.inventoryNumber"
          placeholder="请输入 清查编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label=" 管理部门" prop="managementDepartment">
        <el-input
          v-model="queryParams.managementDepartment"
          placeholder="请输入 管理部门"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label=" 管理人" prop="manager">
        <el-input
          v-model="queryParams.manager"
          placeholder="请输入 管理人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label=" 使用部门" prop="usingDepartment">
        <el-input
          v-model="queryParams.usingDepartment"
          placeholder="请输入 使用部门"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="操作人" prop="op">
        <el-input
          v-model="queryParams.op"
          placeholder="请输入操作人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="操作时间" prop="opDate">
        <el-date-picker clearable
          v-model="queryParams.opDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择操作时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label=" 资产原值" prop="originalValue">
        <el-input
          v-model="queryParams.originalValue"
          placeholder="请输入 资产原值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:assets:add']"
        >新增</el-button>
      </el-col>
      <!-- 新增导入按钮 -->
      <el-col :span="2">
        <el-upload
            class="upload-demo"
            action="/dev-api/system/assets/importData"
            :on-success="handleImportSuccess"
            :on-error="handleImportError"
            :before-upload="beforeUpload"
            :show-file-list="false"
            accept=".xlsx,.xls"
        >
          <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
          >导入</el-button>
        </el-upload>
      </el-col>
      <!-- 新增模板下载按钮 -->
      <el-col :span="2">
        <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="downloadTemplate"
            v-hasPermi="['system:assets:import']"
        >下载模板</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:assets:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:assets:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:assets:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="assetsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label=" 资产编号" align="center" prop="assetNumber" />
      <el-table-column label=" 资产名称" align="center" prop="assetName" />
      <el-table-column label=" 信息卡分类" align="center" prop="infoCardCategory" />
      <el-table-column label=" 资产分类" align="center" prop="assetCategory" />
      <el-table-column label=" 资产分类编码" align="center" prop="assetCategoryCode" />
      <el-table-column label=" 资产门类" align="center" prop="assetClass" />
      <el-table-column label=" 数量/面积" align="center" prop="quantityArea" />
      <el-table-column label=" 取得方式" align="center" prop="acquisitionMethod" />
      <el-table-column label=" 取得日期" align="center" prop="acquisitionDate" />
      <el-table-column label=" 单位名称" align="center" prop="unitName" />
      <el-table-column label=" 清查编号" align="center" prop="inventoryNumber" />
      <el-table-column label=" 业务状态" align="center" prop="businessStatus" />
      <el-table-column label=" 资产状态" align="center" prop="assetStatus" />
      <el-table-column label=" 管理部门" align="center" prop="managementDepartment" />
      <el-table-column label=" 管理人" align="center" prop="manager" />
      <el-table-column label=" 使用部门" align="center" prop="usingDepartment" />
      <el-table-column label="操作人" align="center" prop="op" />
      <el-table-column label="操作时间" align="center" prop="opDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.opDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label=" 资产原值" align="center" prop="originalValue" />
      <el-table-column label="折旧/摊销状态" align="center" prop="depreciationAmortizationStatus" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:assets:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:assets:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改管辖资产对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label=" 资产编号" prop="assetNumber">
          <el-input v-model="form.assetNumber" placeholder="请输入 资产编号" />
        </el-form-item>
        <el-form-item label=" 资产名称" prop="assetName">
          <el-input v-model="form.assetName" placeholder="请输入 资产名称" />
        </el-form-item>
        <el-form-item label=" 信息卡分类" prop="infoCardCategory">
          <el-input v-model="form.infoCardCategory" placeholder="请输入 信息卡分类" />
        </el-form-item>
        <el-form-item label=" 资产分类" prop="assetCategory">
          <el-input v-model="form.assetCategory" placeholder="请输入 资产分类" />
        </el-form-item>
        <el-form-item label=" 资产分类编码" prop="assetCategoryCode">
          <el-input v-model="form.assetCategoryCode" placeholder="请输入 资产分类编码" />
        </el-form-item>
        <el-form-item label=" 资产门类" prop="assetClass">
          <el-input v-model="form.assetClass" placeholder="请输入 资产门类" />
        </el-form-item>
        <el-form-item label=" 数量/面积" prop="quantityArea">
          <el-input v-model="form.quantityArea" placeholder="请输入 数量/面积" />
        </el-form-item>
        <el-form-item label=" 取得方式" prop="acquisitionMethod">
          <el-input v-model="form.acquisitionMethod" placeholder="请输入 取得方式" />
        </el-form-item>
        <el-form-item label=" 取得日期" prop="acquisitionDate">
          <el-input v-model="form.acquisitionDate" placeholder="请输入 取得日期" />
        </el-form-item>
        <el-form-item label=" 单位名称" prop="unitName">
          <el-input v-model="form.unitName" placeholder="请输入 单位名称" />
        </el-form-item>
        <el-form-item label=" 清查编号" prop="inventoryNumber">
          <el-input v-model="form.inventoryNumber" placeholder="请输入 清查编号" />
        </el-form-item>
        <el-form-item label=" 管理部门" prop="managementDepartment">
          <el-input v-model="form.managementDepartment" placeholder="请输入 管理部门" />
        </el-form-item>
        <el-form-item label=" 管理人" prop="manager">
          <el-input v-model="form.manager" placeholder="请输入 管理人" />
        </el-form-item>
        <el-form-item label=" 使用部门" prop="usingDepartment">
          <el-input v-model="form.usingDepartment" placeholder="请输入 使用部门" />
        </el-form-item>
        <el-form-item label="操作人" prop="op">
          <el-input v-model="form.op" placeholder="请输入操作人" />
        </el-form-item>
        <el-form-item label="操作时间" prop="opDate">
          <el-date-picker clearable
            v-model="form.opDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择操作时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label=" 资产原值" prop="originalValue">
          <el-input v-model="form.originalValue" placeholder="请输入 资产原值" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAssets, getAssets, delAssets, addAssets, updateAssets,
  // 新增导入相关API
  importAssets, downloadAssetsTemplate
} from "@/api/system/assets";

export default {
  name: "Assets",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 管辖资产表格数据
      assetsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        assetNumber: null,
        assetName: null,
        infoCardCategory: null,
        assetCategory: null,
        assetCategoryCode: null,
        assetClass: null,
        quantityArea: null,
        acquisitionMethod: null,
        acquisitionDate: null,
        unitName: null,
        inventoryNumber: null,
        businessStatus: null,
        assetStatus: null,
        managementDepartment: null,
        manager: null,
        usingDepartment: null,
        op: null,
        opDate: null,
        originalValue: null,
        depreciationAmortizationStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        assetNumber: [
          { required: true, message: " 资产编号不能为空", trigger: "blur" }
        ],
        assetName: [
          { required: true, message: " 资产名称不能为空", trigger: "blur" }
        ],
        infoCardCategory: [
          { required: true, message: " 信息卡分类不能为空", trigger: "blur" }
        ],
        assetCategory: [
          { required: true, message: " 资产分类不能为空", trigger: "blur" }
        ],
        assetCategoryCode: [
          { required: true, message: " 资产分类编码不能为空", trigger: "blur" }
        ],
        assetClass: [
          { required: true, message: " 资产门类不能为空", trigger: "blur" }
        ],
        quantityArea: [
          { required: true, message: " 数量/面积不能为空", trigger: "blur" }
        ],
        acquisitionMethod: [
          { required: true, message: " 取得方式不能为空", trigger: "blur" }
        ],
        acquisitionDate: [
          { required: true, message: " 取得日期不能为空", trigger: "blur" }
        ],
        unitName: [
          { required: true, message: " 单位名称不能为空", trigger: "blur" }
        ],
        inventoryNumber: [
          { required: true, message: " 清查编号不能为空", trigger: "blur" }
        ],
        businessStatus: [
          { required: true, message: " 业务状态不能为空", trigger: "change" }
        ],
        assetStatus: [
          { required: true, message: " 资产状态不能为空", trigger: "change" }
        ],
        managementDepartment: [
          { required: true, message: " 管理部门不能为空", trigger: "blur" }
        ],
        manager: [
          { required: true, message: " 管理人不能为空", trigger: "blur" }
        ],
        originalValue: [
          { required: true, message: " 资产原值不能为空", trigger: "blur" }
        ],
        depreciationAmortizationStatus: [
          { required: true, message: "折旧/摊销状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询管辖资产列表 */
    getList() {
      this.loading = true;
      listAssets(this.queryParams).then(response => {
        this.assetsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 导入前验证 */
    beforeUpload(file) {
      const isExcel = file.name.endsWith('.xlsx') || file.name.endsWith('.xls');
      if (!isExcel) {
        this.$message.error('只能上传Excel文件！');
        return false;
      }
      // 可以添加文件大小限制
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 2MB!');
        return false;
      }
      this.$modal.loading('正在导入，请稍候...');
      return true;
    },

    /**
     * 处理文件上传
     */
    handleFileUpload(file) {
      const formData = new FormData();
      formData.append('file', file);

      importAssets(formData).then(response => {
        this.$modal.closeLoading();
        this.$message.success(`导入成功，共处理 ${response.data} 条数据`);
        this.getList();
      }).catch(error => {
        this.$modal.closeLoading();
        this.$message.error(error.msg || '导入失败，请重试');
      });
    },

    /** 导入成功处理 */
    handleImportSuccess(response) {
      this.$modal.closeLoading();
      if (response.code === 200) {
        this.$message.success(`导入成功，共处理 ${response.data} 条数据`);
        this.getList(); // 重新加载数据
      } else {
        this.$message.error(response.msg || '导入失败，请检查文件格式和数据！');
      }
    },

    /** 导入失败处理 */
    handleImportError() {
      this.$modal.closeLoading();
      this.$message.error('导入失败，请联系管理员！');
    },

    /** 下载模板 */
    downloadTemplate() {
      window.location.href = '/system/assets/downloadTemplate';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        assetsId: null,
        assetNumber: null,
        assetName: null,
        infoCardCategory: null,
        assetCategory: null,
        assetCategoryCode: null,
        assetClass: null,
        quantityArea: null,
        acquisitionMethod: null,
        acquisitionDate: null,
        unitName: null,
        inventoryNumber: null,
        businessStatus: null,
        assetStatus: null,
        managementDepartment: null,
        manager: null,
        usingDepartment: null,
        op: null,
        opDate: null,
        originalValue: null,
        depreciationAmortizationStatus: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.assetsId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加管辖资产";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const assetsId = row.assetsId || this.ids
      getAssets(assetsId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改管辖资产";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.assetsId != null) {
            updateAssets(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAssets(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const assetsIds = row.assetsId || this.ids;
      this.$modal.confirm('是否确认删除管辖资产编号为"' + assetsIds + '"的数据项？').then(function() {
        return delAssets(assetsIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/assets/export', {
        ...this.queryParams
      }, `assets_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
